<?php session_start(); ?>
<html>
<head>
	<title>Stewie's Market</title>
	<link rel="stylesheet" href="cs2102.css"> 
</head>
<body>
	<div class="container">
	<h1>Welcome to Stewie's Market</h1>
	<form action="index.php" method=get>
		<?php

		if( isset($_SESSION['logged']))
		{
			print_secure_content();
		}else {
			if(!isset($_SESSION["logging"]))
			{  
				$_SESSION["logging"] = true;
				loginform();
			}
			else
			{
				$number_of_rows = checkpass();
				if($number_of_rows == 1)
				{	
					$_SESSION['user'] = strtoupper($_GET['userlogin']);
					$_SESSION['logged'] = true;
					print_secure_content();
				}else{
					print "Wrong username or password, please try again.";	
					loginform();
				}
			}
		}	
		function loginform()
		{
			print ("<p>Please sign in below:</p>");
			print ("<table><tr><td>Matric No</td><td><input type='text' name='userlogin' size'20'></td></tr><tr><td>Password</td><td><input type='password' name='password' size'20'></td></tr></table>");
			print "<input type='submit' value='Login' onsubmit='return formSent()'>";	
			print "<br><br><a href='registerform.php'>Register a new account</a></br>";	
		}

		function checkpass()
		{
			if (!isset($_GET['userlogin']))
				return 0;
			// Open database connection
			$dbHost = "sid3.comp.nus.edu.sg";
			$dbHostPort="1521";
			$dbServiceName = "sid3.comp.nus.edu.sg";
			$usr = "A0103863";
			$pswd = "cs2102std";
			$dbConnStr = "(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=".$dbHost.")(PORT=".$dbHostPort."))(CONNECT_DATA=(SERVICE_NAME=".$dbServiceName.")))";
			$dbConn = oci_connect($usr,$pswd,$dbConnStr);
			if(!$dbConn)
			{
				$err = oci_error();
				print('Could not establish a connection: ' . $err['message']);
			}else {
				$strSQL = "SELECT * FROM student WHERE matric='".strtoupper($_GET['userlogin'])."' AND password='".$_GET['password']."'";
				$stmt = oci_parse($dbConn,$strSQL);
				if ( ! oci_execute($stmt) ){
					$err = oci_error($stmt);
					print('Query failed: '.$err['message']);
				};

				if(oci_fetch($stmt)){
					return oci_num_rows($stmt);
				}
			}
		}

		function print_secure_content()
		{
			header("Location: search.php");
			print "<br><a href='logout.php'>Logout</a><br>";	
		}
		?>
	</form>

	<!-- Sign and date the page, it's only polite! -->
	<address>Made by Project group 31 for CS2102, NUS 2013.</address>
</div>
</body>
</html>